package com.hotel.management.util;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.beans.PropertyDescriptor;
import java.util.HashSet;
import java.util.Set;

/**
 * Bean工具类
 * 提供Bean对象之间的转换和操作功能
 * 
 * @author Hotel Management Team
 * @version 1.0.0
 * @since 2024-06-28
 */
public class BeanUtils {

    /**
     * 私有构造函数，防止实例化
     */
    private BeanUtils() {
        throw new UnsupportedOperationException("Utility class cannot be instantiated");
    }

    /**
     * 复制对象属性，忽略null值
     * 
     * @param source 源对象
     * @param target 目标对象
     */
    public static void copyPropertiesIgnoreNull(Object source, Object target) {
        org.springframework.beans.BeanUtils.copyProperties(source, target, getNullPropertyNames(source));
    }

    /**
     * 获取对象中值为null的属性名数组
     * 
     * @param source 源对象
     * @return null属性名数组
     */
    public static String[] getNullPropertyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<>();
        for (PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) {
                emptyNames.add(pd.getName());
            }
        }

        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

    /**
     * 复制对象属性
     * 
     * @param source 源对象
     * @param target 目标对象
     */
    public static void copyProperties(Object source, Object target) {
        org.springframework.beans.BeanUtils.copyProperties(source, target);
    }

    /**
     * 复制对象属性，忽略指定属性
     * 
     * @param source 源对象
     * @param target 目标对象
     * @param ignoreProperties 要忽略的属性名
     */
    public static void copyProperties(Object source, Object target, String... ignoreProperties) {
        org.springframework.beans.BeanUtils.copyProperties(source, target, ignoreProperties);
    }

    /**
     * 检查对象是否为null或所有属性都为null
     * 
     * @param obj 要检查的对象
     * @return 如果对象为null或所有属性都为null则返回true
     */
    public static boolean isNullOrEmpty(Object obj) {
        if (obj == null) {
            return true;
        }

        final BeanWrapper wrapper = new BeanWrapperImpl(obj);
        PropertyDescriptor[] pds = wrapper.getPropertyDescriptors();

        for (PropertyDescriptor pd : pds) {
            // 跳过class属性
            if ("class".equals(pd.getName())) {
                continue;
            }
            Object value = wrapper.getPropertyValue(pd.getName());
            if (value != null) {
                return false;
            }
        }

        return true;
    }
}
